import moment from 'moment';
import * as CryptoJS from 'crypto-js';

function formatFileSize(size: number | string, unit?: "M" | "K"): string {
  if (unit === "K") {
    return (+size / (1024 * 1024 * 1024)).toFixed(2) + "K"
  }
  return (+size / (1024 * 1024)).toFixed(1) + "M"
}

function formatDuration({
  duration,
  unit,
  format,
}: {
  duration: number;
  unit?: string;
  format?: string;
}) {
  return (
    moment
      // @ts-ignore
      .duration(duration, unit || 'milliseconds')
      // @ts-ignore
      .format(format || 'mm:ss', { trim: false })
  );
}



function getRandomItemFromArray<T>(array: T[]): T | undefined {
  if (array.length <= 0) return undefined;
  return array[Math.floor(array.length * Math.random())];
}

function uuid(length: number = 30, prefix: string = '') {
  let guid = '';
  for (let i = 1; i <= length; i++) {
    let n = Math.floor(Math.random() * 16.0).toString(16);
    guid += n;
  }
  return `${prefix ? `${prefix}-` : ''}${guid}`;
}



function md5(d: string | number) {
  return CryptoJS.MD5(d.toString()).toString()
}

function getArray(length?: number) {
  return Array.from(new Array(length || 10).keys())
}

function equalString(a: any, b: any): boolean {
  return `${a}` === `${b}`
}

function clone<T>(_: T): T {
  return JSON.parse(JSON.stringify(_))
}




const $helper = {
  uuid, getRandomItemFromArray, formatDuration,
  md5, getArray, equalString,
  clone, formatFileSize,
}

export default $helper
